package com.emm.yixun.customer.service.impl;
import java.util.List;

import javax.jws.WebService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.emm.yixun.basic.service.QuestionnaireAnswerService;
import com.emm.yixun.basic.service.QuestionnaireModelService;
import com.emm.yixun.basic.service.QuestionnaireQuestionService;
import com.emm.yixun.common.exception.ResponseCode;
import com.emm.yixun.common.model.QuestionnaireAnswer;
import com.emm.yixun.common.model.QuestionnaireModel;
import com.emm.yixun.common.model.QuestionnaireModelInfo;
import com.emm.yixun.common.model.QuestionnaireQuestion;
import com.emm.yixun.common.model.dto.QuestionnaireAnswerDto;
import com.emm.yixun.common.model.dto.QuestionnaireModelDto;
import com.emm.yixun.common.model.dto.QuestionnaireQuestionDto;
import com.emm.yixun.common.model.enums.DelFlagEnum;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.customer.service.QuestionnaireModelServiceFacade;

@Service("questionnaireModelServiceFacade")
@WebService(name="com.emm.yixun.customer.service.QuestionnaireModelServiceFacade")
public class QuestionnaireModelServiceFacadeImpl implements QuestionnaireModelServiceFacade{
	private  final Logger   logger = LoggerFactory.getLogger(this.getClass()); 
	
	@Autowired
	private QuestionnaireModelService service;
	
	@Autowired
	private QuestionnaireQuestionService questionnaireQuestionService;
	
	@Autowired
	private QuestionnaireAnswerService questionnaireAnswerService;
	

	@Override
	public Response<QuestionnaireModelDto> save(QuestionnaireModelDto dto) {
		Response<QuestionnaireModelDto> response=new Response<QuestionnaireModelDto>();
		try {
			if(null==dto){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("保存"));
				return response;
			}
			QuestionnaireModelDto mDto=service.create(dto);
			if(null==mDto){
				response.fail("80000", "保存数据错误");
				return response;
			}
			response.success(mDto);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("保存数据错误：{}",e);
		}
		return response;
	}

	@Override
	public Response<Integer> updateByPrimaryKey(QuestionnaireModelDto dto,Boolean selective) {
		Response<Integer> response=new Response<Integer>();
		try {
			if(null==selective || null==dto || null==dto.getId()){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("更新"));
				return response;
			}
			
			if(selective){
				int count=service.update(dto);
				if(count>0){
					response.success(Integer.valueOf(count));
					//当编辑内容为删除时，同时删除问卷问题及答案
					if(DelFlagEnum.DEL.getNo().equals(dto.getDelFlag())){
						deleteQuestion(dto.getId());
					}
				}else{
					response.fail("90001", "更新数据失败");
				}
			}else{
				response.fail("90000", "暂未实现,修改参数selective=true即可");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("更新数据错误：{}",e);
		}
		return response;
	}
	/**
	 * 逻辑删除问卷问题
	 */
	private void deleteQuestion(Long id){
		QuestionnaireQuestionDto entity = new QuestionnaireQuestionDto();
		entity.setQuestionnaireModelId(id);
		List<QuestionnaireQuestion> list = questionnaireQuestionService.selectListByDto(entity);
		for(QuestionnaireQuestion qq : list){
			QuestionnaireQuestionDto dto = new QuestionnaireQuestionDto();
			dto.setId(qq.getId());
			dto.setDelFlag(DelFlagEnum.DEL.getNo());
			questionnaireQuestionService.update(dto);
			//逻辑删除问卷答案
			deleteAnswer(qq.getId());
		}
	}
	/**
	 * 逻辑删除问卷答案
	 */
	private void deleteAnswer(Long id){
		QuestionnaireAnswerDto entity = new QuestionnaireAnswerDto();
		entity.setQuestionnaireQuestionId(id);
		List<QuestionnaireAnswer> list = questionnaireAnswerService.selectListByDto(entity);
		for(QuestionnaireAnswer qa : list){
			QuestionnaireAnswerDto dto = new QuestionnaireAnswerDto();
			dto.setId(qa.getId());
			dto.setDelFlag(DelFlagEnum.DEL.getNo());
			questionnaireAnswerService.update(dto);
		}
	}

	@Override
	public Response<Integer> deleteByPrimaryKey(Long id) {
		Response<Integer> response=new Response<Integer>();
		try {
			if(null==id){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("删除"));
				return response;
			}
			QuestionnaireModelDto mDto=new QuestionnaireModelDto();
			mDto.setId(id);
			int count=service.destroy(mDto);
			if(count>0){
				response.success(Integer.valueOf(count));
			}else{
				response.fail("90001", "删除数据失败");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("删除数据错误：{}",e);
		}
		return response;
	}
	
    @Override
	public Response<QuestionnaireModel> findById(Long id) {
		Response<QuestionnaireModel> response=new Response<QuestionnaireModel>();
		try {
			if(null==id){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("主键查询"));
				return response;
			}
			QuestionnaireModel entity=service.selectById(id);
			if(null==entity){
				response.fail("90001", "主键查询数据失败");
			}else{
				response.success(entity);;
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("主键查询数据错误：{}",e);
		}
		return response;
	}

	@Override
	public ResponseList<QuestionnaireModel> findByDto(QuestionnaireModelDto dto) {
		ResponseList<QuestionnaireModel> response=new ResponseList<QuestionnaireModel>();
		try {
			if(null==dto){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			List<QuestionnaireModel> list=service.selectListByDto(dto);
			if(null==list){
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}",e);
		}
		return response;
	}
	
	@Override
	public Page<QuestionnaireModel> findPageByDto(QuestionnaireModelDto dto, Integer begin,Integer row) {
		Page<QuestionnaireModel> response = new Page<QuestionnaireModel>();
		try {
			if(null==dto || null==begin || null==row){
				response.setSuccess(false);
				response.setErrorMsg("参数不合法");
				return response;
			}
			Page<QuestionnaireModel> page = service.getPageModel(dto, begin, row);
			if(null==page.getRows()){
				response.setSuccess(false);
				response.setErrorMsg("分页数据不存在");
				return response;
			}
			response = page;
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询分页数据错误：{}",e);
		}
		return response;
	}

	@Override
	public Page<QuestionnaireModelInfo> findPageInfoByDto(QuestionnaireModelDto dto, Integer begin,Integer row) {
		Page<QuestionnaireModelInfo> response = new Page<QuestionnaireModelInfo>();
		try {
			if(null==dto || null==begin || null==row){
				response.setSuccess(false);
				response.setErrorMsg("参数不合法");
				return response;
			}
			Page<QuestionnaireModelInfo> page = service.getPageModelInfo(dto, begin, row);
			if(null==page.getRows()){
				response.setSuccess(false);
				response.setErrorMsg("分页数据不存在");
				return response;
			}
		    
			response = page;
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询分页数据错误：{}",e);
		}
		return response;
	}

	@Override
	public Response<QuestionnaireModelDto> saveInfo(QuestionnaireModelDto dto, Long copyId) {
		Response<QuestionnaireModelDto> response=new Response<QuestionnaireModelDto>();
		try {
			if(null==dto){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("保存"));
				return response;
			}
			QuestionnaireModelDto entity = new QuestionnaireModelDto();  
    		entity.setName(dto.getName());
    		entity.setMerchantId(dto.getMerchantId());
    		entity.setDelFlag("0");
    		List<QuestionnaireModel> list = service.selectListByDto(entity);
    		if(list != null && list.size() > 0){
    			response.fail("0000", "该名称已有重复问卷，请更换问卷名称后再保存");
    			return response;
    		}
			QuestionnaireModelDto mDto = service.create(dto);
			if(null==mDto){
				response.fail("80000", "保存数据错误");
				return response;
			}
			if(copyId != null){
				copyQuestionnaireQuestion(dto.getId(), copyId);
			}
			response.success(mDto);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("保存数据错误：{}",e);
		}
		return response;
	}
	
	/**
	 * 复制问题
	 * @param id
	 * @param copyId
	 */
	private void copyQuestionnaireQuestion(Long id, Long copyId){
		QuestionnaireQuestionDto entity = new QuestionnaireQuestionDto();
		entity.setQuestionnaireModelId(copyId);
		entity.setDelFlag("0");
		List<QuestionnaireQuestion> list = questionnaireQuestionService.selectListByDto(entity);
		for(QuestionnaireQuestion qq : list){
			QuestionnaireQuestionDto info = new QuestionnaireQuestionDto();
			BeanUtils.copyProperties(qq, info);
			info.setQuestionnaireModelId(id);
			QuestionnaireQuestionDto dto = questionnaireQuestionService.create(info);
			//复制答案
			copyQuestionnaireAswer(dto.getId(), qq.getId());
		}
	}
	/**
	 * 复制答案
	 * @param id
	 * @param copyId
	 */
	private void copyQuestionnaireAswer(Long id, Long copyId){
		QuestionnaireAnswerDto entity = new QuestionnaireAnswerDto();
		entity.setQuestionnaireQuestionId(copyId);
		entity.setDelFlag("0");
		List<QuestionnaireAnswer> list = questionnaireAnswerService.selectListByDto(entity);
		for(QuestionnaireAnswer qa : list){
			QuestionnaireAnswerDto info = new QuestionnaireAnswerDto();
			BeanUtils.copyProperties(qa, info);
			info.setQuestionnaireQuestionId(id);
			questionnaireAnswerService.create(info);
		}
	}
}
